package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseRestartDialogFragment;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.ConfigOrignal;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.LocalConfigOriginal;
import com.isunland.managesystem.entity.MaterialMunit;
import com.isunland.managesystem.entity.MaterielLomContent;
import com.isunland.managesystem.entity.RInappMain;
import com.isunland.managesystem.entity.RInappSub;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.MyViewUtil;
import com.isunland.managesystem.utils.NumberUtil;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/7/18 17:16
 */
public class InMaterieDetailFragment extends BaseFragment {
  public static final String EXTRA_MAIN_CONTENT =
      InMaterieDetailFragment.class.getSimpleName() + "EXTRA_MAIN_CONTENT";
  public static final String EXTRA_SUB_CONTENT =
      InMaterieDetailFragment.class.getSimpleName() + "EXTRA_SUB_CONTENT";

  @BindView(R.id.slv_materialKindName) SingleLineView slvMaterialKindName;
  @BindView(R.id.slv_materialName) SingleLineView slvMaterialName;
  @BindView(R.id.slv_inbillCode) SingleLineView slvInbillCode;
  @BindView(R.id.slv_materialSelfCode) SingleLineView slvMaterialSelfCode;
  @BindView(R.id.slv_mtype) SingleLineView slvMtype;
  @BindView(R.id.slv_munit) SingleLineView slvMunit;
  @BindView(R.id.slv_minPrice) SingleLineView slvMinPrice;
  @BindView(R.id.slv_inappNumber) SingleLineView slvInappNumber;
  @BindView(R.id.slv_minsumPrice) SingleLineView slvMinsumPrice;
  @BindView(R.id.slv_inbillBatch) SingleLineView slvInbillBatch;
  @BindView(R.id.slv_mfactoryName) SingleLineView slvMfactoryName;
  @BindView(R.id.slv_mprodnum) SingleLineView slvMprodnum;
  @BindView(R.id.slv_mproddate) SingleLineView slvMproddate;
  @BindView(R.id.slv_mexpDate) SingleLineView slvMexpDate;
  @BindView(R.id.slv_minRecnum) SingleLineView slvMinRecnum;
  @BindView(R.id.slv_remark) SingleLineView slvRemark;
  @BindView(R.id.slv_inRelformNo) SingleLineView slvInRelformNo;

  protected static final int CHOOSE_MATERIE = 1;
  protected static final int DETAIL_MATERIEL = 2;
  protected static final int DELETE_MATERIEL = 3;
  protected static final int SAVE_MATERIEL = 4;
  protected static final int CHOOSE_CATEGORY = 5;
  private int REQUEST_MUNIT = 6;

  private int menuType;
  private int ADD = 0;
  private int DETAIL = 1;
  private int PUBLISH = 2;
  private RInappMain inMain;
  private RInappSub inSub;
  private static HashMap<String, LocalConfigOriginal.LocalConfigModel> mConfigMap;
  private String mId;
  protected String materialKindCode = "";//物料类别id
  private String materialId;
  private String conversionRelationship;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom("物品清单详情");
    inMain = (RInappMain) getArguments().getSerializable(EXTRA_MAIN_CONTENT);
    inSub = (RInappSub) getArguments().getSerializable(EXTRA_SUB_CONTENT);
    mConfigMap = new HashMap<>();
    if (inSub == null) {
      mId = UUID.randomUUID().toString();
      menuType = ADD;
      conversionRelationship = "1";
    } else {
      mId = inSub.getId();
      materialId = inSub.getMaterialId();
      materialKindCode = inSub.getMaterialKindCode();
      conversionRelationship = TextUtils.isEmpty(inSub.getConversionRelationship()) ? "1"
          : inSub.getConversionRelationship();
      if (DataStatus.NEW.equalsIgnoreCase(inMain.getMinbillStatusCode())
          || DataStatus.ABORT.equalsIgnoreCase(inMain.getMinbillStatusCode())) {
        menuType = DETAIL;
      } else {
        menuType = PUBLISH;
      }
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if (menuType == ADD) {
      inflater.inflate(R.menu.menu_save_delete, menu);
      menu.getItem(1).setVisible(false);
    } else if (menuType == DETAIL) {
      inflater.inflate(R.menu.menu_save_delete, menu);
    } else {
      super.onCreateOptionsMenu(menu, inflater);
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();

        break;
      //保存
      case R.id.menu_item_save:
        if (isCorrectInput()) {
          volleyPoastSave();
        }
        break;
      //删除物料明细
      case R.id.menu_item_delete:
        showDialog(DELETE_MATERIEL);
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override protected int initLayoutId() {
    return R.layout.fragment_inmaterial_detail;
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View rootView = super.onCreateView(inflater, container, savedInstanceState);
    ButterKnife.bind(this, rootView);
    //动态配置界面
    volleyPostConfig(rootView);
    return rootView;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    if (inSub != null) {
      slvMaterialKindName.setTextContent(inSub.getMaterialKindName());
      slvMaterialName.setTextContent(inSub.getMaterialName());
      slvInbillCode.setTextContent(inSub.getInbillCode());
      slvMaterialSelfCode.setTextContent(inSub.getMaterialSelfCode());
      slvMtype.setTextContent(inSub.getMtype());
      slvMunit.setTextContent(inSub.getMunit());
      slvMinPrice.setTextContent(inSub.getMinPrice().toString());
      slvInappNumber.setTextContent(inSub.getInappNumber().toString());
      slvMinsumPrice.setTextContent(inSub.getMinsumPrice().toString());
      slvInbillBatch.setTextContent(inSub.getInbillBatch());
      slvMfactoryName.setTextContent(inSub.getMfactoryName());
      slvMprodnum.setTextContent(inSub.getMprodnum());
      slvMproddate.setTextContent(inSub.getMproddate());
      slvMexpDate.setTextContent(inSub.getMexpDate());
      slvMinRecnum.setTextContent(inSub.getMinRecnum().toString());
      slvRemark.setTextContent(inSub.getRemark());
      slvInRelformNo.setTextContent(inSub.getInRelformNo());
    } else {
      //添加
      slvInappNumber.setTextContent("1.00");
      slvInbillBatch.setTextContent(MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE6));//入库批次
      slvMinRecnum.setTextContent("0");//入库记录数
    }
    if (PUBLISH == menuType) {
      MyViewUtil.setEnableAll(false, slvMaterialKindName.getTvContent(),
          slvMaterialName.getTvContent(), slvInbillCode.getTvContent(),
          slvMaterialSelfCode.getTvContent(), slvMtype.getTvContent(), slvMunit.getTvContent(),
          slvMinPrice.getTvContent(), slvInappNumber.getTvContent(), slvMinsumPrice.getTvContent(),
          slvInbillBatch.getTvContent(), slvMfactoryName.getTvContent(), slvMprodnum.getTvContent(),
          slvMproddate.getTvContent(), slvMexpDate.getTvContent(), slvMinRecnum.getTvContent(),
          slvRemark.getTvContent(), slvInRelformNo.getTvContent());
    }
    //物料类别
    slvMaterialKindName.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(CHOOSE_CATEGORY);
      }
    });
    //物料名称
    slvMaterialName.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        if (TextUtils.isEmpty(slvMaterialKindName.getTextContent())) {
          ToastUtil.show(R.string.choose_kind);
        } else {
          showDialog(CHOOSE_MATERIE);
        }
      }
    });
    //单位
    slvMunit.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        if (!TextUtils.isEmpty(materialId)) {
          mBaseParams.setId(materialId);
          MunitListActivity.newInstance(InMaterieDetailFragment.this, MunitListActivity.class,
              mBaseParams, REQUEST_MUNIT);
        }
      }
    });
    //生产日期
    slvMproddate.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(BaseYMDTimeDialogFragment.newInstance(new Date())
            .setCallBack(new BaseYMDTimeDialogFragment.CallBack() {
              @Override public void select(Date date) {
                slvMproddate.setTextContent(MyDateUtil.format(date, MyDateUtil.TYPE_DATE));
              }
            }));
      }
    });
    //有效期
    slvMexpDate.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(BaseYMDTimeDialogFragment.newInstance(new Date())
            .setCallBack(new BaseYMDTimeDialogFragment.CallBack() {
              @Override public void select(Date date) {
                slvMexpDate.setTextContent(MyDateUtil.format(date, MyDateUtil.TYPE_DATE));
              }
            }));
      }
    });
    //监听文字改变
    slvMinPrice.getTvContent().addTextChangedListener(textWatcher);
    slvInappNumber.getTvContent().addTextChangedListener(textWatcher);
  }

  /*判断必填项*/
  private boolean isCorrectInput() {

    if (slvMaterialKindName.getVisibility() == View.VISIBLE && TextUtils.isEmpty(
        slvMaterialKindName.getTextContent())) {
      ToastUtil.show(R.string.notComplete);
      return false;
    }
    if (slvMaterialName.getVisibility() == View.VISIBLE && TextUtils.isEmpty(
        slvMaterialName.getTextContent())) {
      ToastUtil.show(R.string.notComplete);
      return false;
    }
    if (slvMunit.getVisibility() == View.VISIBLE && TextUtils.isEmpty(slvMunit.getTextContent())) {
      ToastUtil.show(R.string.notComplete);
      return false;
    }
    if (slvInappNumber.getVisibility() == View.VISIBLE && TextUtils.isEmpty(
        slvInappNumber.getTextContent())) {
      ToastUtil.show(R.string.notComplete);
      return false;
    }
    return true;
  }

  private TextWatcher textWatcher = new TextWatcher() {

    @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
      try {
        Double number;
        Double price;
        number = TextUtils.isEmpty(slvInappNumber.getTextContent()) ? 0.0
            : Double.parseDouble(slvInappNumber.getTextContent());
        price = TextUtils.isEmpty(slvMinPrice.getTextContent()) ? 0.0
            : Double.parseDouble(slvMinPrice.getTextContent());
        slvMinsumPrice.setTextContent(NumberUtil.numberBigToString(number * price));
      } catch (NumberFormatException e) {
        e.printStackTrace();
      }
    }

    @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override public void afterTextChanged(Editable s) {
    }
  };

  @SuppressWarnings("static-access") protected void showDialog(int requestCode) {

    DialogFragment dialog = null;
    switch (requestCode) {

      //选择物料类别
      case CHOOSE_CATEGORY:
        dialog = new MaterielDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("type", MaterielDialogFragment.type_catragory);
        bundle.putSerializable("customerId", inMain.getMsupplyId());
        bundle.putSerializable("storageId", inMain.getStorageId());
        bundle.putSerializable("kindId", inMain.getMaterialKindCode());
        dialog.setArguments(bundle);
        break;
      //选择物料名称
      case CHOOSE_MATERIE:
        dialog = new MaterielDialogFragment();
        Bundle bundle2 = new Bundle();
        bundle2.putSerializable("type", MaterielDialogFragment.type_materiel);
        bundle2.putSerializable("customerId", inMain.getMsupplyId());
        bundle2.putSerializable("storageId", inMain.getStorageId());
        bundle2.putSerializable("kindId", materialKindCode);
        dialog.setArguments(bundle2);

        break;

      case DELETE_MATERIEL:
        dialog = new BaseRestartDialogFragment().newInstance(R.string.deleteConfirm,
            R.string.restart_title);
        break;

      case SAVE_MATERIEL:
        dialog =
            new BaseRestartDialogFragment().newInstance(R.string.ifSave, R.string.restart_title);
        break;

      default:
        break;
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    if (dialog == null) return;
    dialog.setTargetFragment(this, requestCode);
    dialog.show(fm, "");
  }

  private void volleyPostConfig(final View rootView) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DYNAMIC_CONFIG);
    ParamsNotEmpty params = new ParamsNotEmpty();
    /**
     零购入库申请子表配置：
     参数：resourceFlag: inBill_LG

     零售出库申请子表配置：
     参数：resourceFlag: outBill_Sale

     物料生产出库申请子表配置：
     参数：resourceFlag：outBill_Material

     工器具领用出库申请子表配置：
     参数：resourceFlag：outBill_Tool

     */
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("resourceFlag", "inBill_LG");
    params.put("dataStatus", "publish");
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        ConfigOrignal configOriginal = new Gson().fromJson(arg0, ConfigOrignal.class);
        arg0 = configOriginal.getRows().get(0).getContentApp().replace("\\", "");
        LogUtil.i("本地配置=" + arg0);
        LocalConfigOriginal.LocalConfigModel[] rows =
            new Gson().fromJson(arg0, LocalConfigOriginal.LocalConfigModel[].class);

        for (LocalConfigOriginal.LocalConfigModel dynamicConfig : rows) {
          if (dynamicConfig != null) {
            mConfigMap.put(dynamicConfig.getField(), dynamicConfig);
          }
        }
        for (String tag : mConfigMap.keySet()) {
          SingleLineView lineView = (SingleLineView) rootView.findViewWithTag(tag);
          if (lineView != null) {
            LocalConfigOriginal.LocalConfigModel config = mConfigMap.get(tag);
            //设置显示和隐藏
            lineView.setVisibility(config.isHidden() ? View.GONE : View.VISIBLE);
            //设置标题
            lineView.setTextTitle(
                (config.getTitle().contains(":") || config.getTitle().contains("："))
                    ? config.getTitle() : MyStringUtil.connect(config.getTitle(), "："));
            //设置是否可编辑,不可编辑可点击
            lineView.getTvContent().setFocusable(config.isIfedit());
            lineView.getTvContent().setClickable(true);
          }
        }
      }
    });
  }

  /*保存*/
  private void volleyPoastSave() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RETAIL_IN_SUB_SAVE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    params.put("mainid", inMain.getId());
    params.put("materialKindCode", materialKindCode);
    params.put("materialKindName", slvMaterialKindName.getTextContent());
    params.put("materialId", materialId);
    params.put("materialName", slvMaterialName.getTextContent());
    params.put("inbillCode", slvInbillCode.getTextContent());
    params.put("materialSelfCode", slvMaterialSelfCode.getTextContent());
    params.put("mtype", slvMtype.getTextContent());
    params.put("munit", slvMunit.getTextContent());
    params.put("minPrice", slvMinPrice.getTextContent());
    params.put("conversionRelationship", conversionRelationship);//当前单位是标准单位（N倍）
    double number = TextUtils.isEmpty(slvInappNumber.getTextContent()) ? 0.0
        : Double.parseDouble(slvInappNumber.getTextContent());
    double minNumber = number * Double.parseDouble(conversionRelationship);
    params.put("minNumber",
        String.valueOf(minNumber));//入库库存中的标准数量 minNumber=inappNumber*conversionRelationship;
    params.put("inappNumber", slvInappNumber.getTextContent());//申请数量
    params.put("minsumPrice", TextUtils.isEmpty(slvMinsumPrice.getTextContent()) ? "0"
        : slvMinsumPrice.getTextContent());//总价
    params.put("inbillBatch", slvInbillBatch.getTextContent());
    params.put("mfactoryName", slvMfactoryName.getTextContent());
    params.put("mprodnum", slvMprodnum.getTextContent());
    params.put("mproddate", slvMproddate.getTextContent());
    params.put("mexpDate", slvMexpDate.getTextContent());
    params.put("minRecnum", slvMinRecnum.getTextContent());
    params.put("remark", slvRemark.getTextContent());
    params.put("inRelformNo", slvInRelformNo.getTextContent());

    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  private VolleyResponse getResponse() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String json) throws JSONException {

        try {
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(json, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            ToastUtil.show(R.string.success_operation);

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }
    };
  }

  //删除物料明细
  private void volleyPoastDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RETAIL_IN_SUB_DEL);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == CHOOSE_MATERIE) {
      //物料名称
      MaterielLomContent content =
          (MaterielLomContent) data.getSerializableExtra(MaterielDialogFragment.EXTRA_VALUE);
      materialId = content.getId();
      conversionRelationship = "1";
      slvMaterialName.setTextContent(content.getName());
      slvInbillCode.setTextContent(content.getCustomAttrs());
      slvMaterialSelfCode.setTextContent(content.getFlag());
      slvMtype.setTextContent(content.getExtParam());//规格型号
      slvMunit.setTextContent(content.getExtParam2());//基本单位
      //如果返回的单价为空可编辑，不为空就不可编辑
      if (!TextUtils.isEmpty(content.getExtParam4())) {
        slvMinPrice.setEnabled(false);
      } else {
        slvMinPrice.setEnabled(true);
      }
      slvMinPrice.setTextContent(content.getExtParam4());//单价
    }
    if (requestCode == CHOOSE_CATEGORY) {
      //物料类别
      MaterielLomContent content =
          (MaterielLomContent) data.getSerializableExtra(MaterielDialogFragment.EXTRA_VALUE);
      slvMaterialKindName.setTextContent(content.getName());
      materialKindCode = content.getId();
      conversionRelationship = "1";
      materialId = "";
      //如果重新选择物料类别
      slvMaterialName.setTextContent("");
      slvInbillCode.setTextContent("");
      slvMaterialSelfCode.setTextContent("");
      slvMtype.setTextContent("");//规格型号
      slvMunit.setTextContent("");//基本单位
      slvMinPrice.setTextContent("");//单价
      slvInappNumber.setTextContent("");//库存数量
    }

    if (requestCode == REQUEST_MUNIT) {
      //物料单位
      MaterialMunit content = (MaterialMunit) data.getSerializableExtra(BaseFragment.EXTRA_PARAMS);
      slvMunit.setTextContent(content.getUnitName());
      conversionRelationship = TextUtils.isEmpty(content.getConversionRelationship()) ? "1"
          : content.getConversionRelationship();
    }
    if (requestCode == DETAIL_MATERIEL) {
      getActivity().setResult(Activity.RESULT_OK);
      getActivity().finish();
    }
    if (requestCode == DELETE_MATERIEL) {
      volleyPoastDelete();
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  public static InMaterieDetailFragment newInstance(RInappMain inMain, RInappSub inSub) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_MAIN_CONTENT, inMain);
    args.putSerializable(EXTRA_SUB_CONTENT, inSub);
    InMaterieDetailFragment fragment = new InMaterieDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
